package com.mind.adjust.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.mind.adjust.domain.vo.PatchUpdate;
import com.mind.common.utils.poi.ExcelUtil;
import com.mind.common.utils.poi.ImportExcelResult;
import com.mind.common.utils.poi.ValidationUtils;
import com.mind.system.domain.AjRuleCheck;
import com.mind.adjust.service.AjRuleCheckService;
import com.mind.common.web.controller.BaseController;
import com.mind.common.core.domain.AjaxResult;
import com.mind.common.web.page.TableDataInfo;
import com.mind.common.log.annotation.Log;
import com.mind.common.log.enums.BusinessType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolation;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 智能审核模块/审核模块/规则复核管理
 *
 * @author makejava
 * @DocView.PathPrefix {{host}}/api/adjust
 * @since 2024-12-12 11:04:39
 */
@RestController
@RequestMapping("adjust/ruleCheck")
public class AjRuleCheckController extends BaseController {
    /**
     * 服务对象
     */
    @Autowired
    private AjRuleCheckService ajRuleCheckService;

    /**
     * 获取规则复核列表
     *
     * @param ruleCheck 筛选条件
     * @return com.mind.system.domain.AjRuleCheck
     */
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:list')")
    @Log(title = "规则复核列表", businessType = BusinessType.QUERY)
    @GetMapping("/list")
    public TableDataInfo list(AjRuleCheck ruleCheck)
    {
        startPage();
        List<AjRuleCheck> list = ajRuleCheckService.selectRuleCheckList(ruleCheck);
        return getDataTable(list);
    }
    
    /**
     * 规则复核导入
     *
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:import')")
    @Log(title = "规则复核导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importExcel(MultipartFile file) throws IOException {
        List<AjRuleCheck> cachedDataList = new ArrayList<>();
        List<ImportExcelResult> errorList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), AjRuleCheck.class, new ReadListener<AjRuleCheck>() {

            @Override
            public void invoke(AjRuleCheck data, AnalysisContext context) {
                Set<ConstraintViolation<AjRuleCheck>> violations = ValidationUtils.getValidator().validate(data);
                if(violations.size() > 0){
                    throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), 0, null, null, "");
                }
                cachedDataList.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                saveData();
            }

            /**
             * 加上存储数据库
             */
            private void saveData() {
                int i = ajRuleCheckService.batchInsert(cachedDataList);
            }

            /**
             * 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
             *
             * @param exception
             * @param context
             * @throws Exception
             */
            @Override
            public void onException(Exception exception, AnalysisContext context) {
                // 如果是某一个单元格的转换异常 能获取到具体行号
                // 如果要获取头的信息 配合invokeHeadMap使用
                if (exception instanceof ExcelDataConvertException) {
                    ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
                    String errMsg = String.format("第%d行数据验证异常", excelDataConvertException.getRowIndex());
                    errorList.add(new ImportExcelResult(){{
                        setRow(excelDataConvertException.getRowIndex());
                        setCol(excelDataConvertException.getColumnIndex());
                        setError(errMsg);
                    }});
                }
            }
        }).sheet().doRead();
        if(errorList.size() > 0) {
            return AjaxResult.success(String.format("一共%d条，成功导入%d条，错误%d条。错误详情：%s", cachedDataList.size() + errorList.size(), cachedDataList.size(), errorList.size(), errorList.stream().map(ImportExcelResult::getError).collect(Collectors.joining("\r\n"))));
        }else{
            return AjaxResult.success(String.format("一共%d条，成功导入%d条，错误0条。", (cachedDataList.size()), cachedDataList.size()));
        }
    }

    /**
     * 附件类型下载模板
     * @return 结果
     */
    @Log(title = "规则复核下载模板", businessType = BusinessType.DOWNLOAD)
    @PreAuthorize("@ss.hasPermi('adjust:attachType:download')")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<AjRuleCheck> util = new ExcelUtil<>(AjRuleCheck.class);
        String fileName =  URLEncoder.encode("规则复核模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        util.exportExcel(response, new ArrayList<>(), "规则复核数据");
    }
    
    /**
     * 规则复核导出
     * @param ruleCheck 筛选条件
     * @return 结果
     */
    @Log(title = "规则复核导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, AjRuleCheck ruleCheck)
    {
        List<AjRuleCheck> list = ajRuleCheckService.selectRuleCheckList(ruleCheck);
        ExcelUtil<AjRuleCheck> util = new ExcelUtil<AjRuleCheck>(AjRuleCheck.class);
        util.exportExcel(response, list, "规则复核数据");
    }

    /**
     * 根据ID获取规则复核详情
     * @return com.mind.system.domain.AjRuleCheck
     */
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:query')")
    @GetMapping(value = "/{ruleCheckId}")
    public AjaxResult getInfo(@PathVariable Long ruleCheckId)
    {
        return success(ajRuleCheckService.selectRuleCheckById(ruleCheckId));
    }

    /**
     * 新增规则复核
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:add')")
    @Log(title = "规则复核新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody AjRuleCheck ruleCheck)
    {
        return toAjax(ajRuleCheckService.insertRuleCheck(ruleCheck));
    }

    /**
     * 修改规则复核
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:edit')")
    @Log(title = "规则复核修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody AjRuleCheck ruleCheck)
    {
        return toAjax(ajRuleCheckService.updateRuleCheck(ruleCheck));
    }

    /**
     * 批量通过/驳回
     * @return 结果
     */
//    @RequiresPermissions("adjust:ruleCheck:edit")
    @Log(title = "规则复核修改", businessType = BusinessType.UPDATE)
    @PostMapping("patchCheck")
    public AjaxResult patch(@Validated @RequestBody PatchUpdate params)
    {
        return toAjax(ajRuleCheckService.patchCheck(params));
    }

    /**
     * 删除规则复核
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('adjust:ruleCheck:remove')")
    @Log(title = "规则复核删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ruleCheckIds}")
    public AjaxResult remove(@PathVariable Long[] ruleCheckIds)
    {
        return toAjax(ajRuleCheckService.deleteRuleCheckByIds(ruleCheckIds));
    }

}


